<?php


namespace App\Http\Controllers;


use App\Models\RcMessage;
use Carbon\Carbon;
use GuzzleHttp\Client;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;

class RcMessageController extends Controller
{

    public function create(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'appointment_time' => 'required',
            'name' => 'required',
            'phone' => 'required',
            'city' => 'required',
            'dealer' => 'required',
            'car' => 'required',
            'province' => 'required',
            'code' => 'required',
        ]);

        if ($validator->fails()) {
            return $this->error($validator->errors()->first());
        }
        $data = $request->input();
        try {
//            $model_count = RcMessage::query()->where('phone',$data['phone'])->whereBetween('created_at',[Carbon::now()->startOfDay(),Carbon::now()->endOfDay()])->count();
//            if ($model_count >= 2){
//                return  $this->error('每天只能预约两次，明天再来吧~');
//            }
            $model_count = RcMessage::query()->where('phone',$data['phone'])->count();

            if ($model_count){
                return  $this->error('已有预约记录');
            }
            $login = $this->login($data);
            if ($login->code != 0){
                return $this->error($login->msg);
            }
            $app_data = [
                'dealership_code'=>$data['dealer'],
                'name'=>$data['name'],
                'mobile'=>$data['phone'],
                'code'=>$data['code'],
                'car_style_id'=>(int)$data['car'],
                'appointment_time'=>$data['appointment_time'],
                'token'=>$login->data->token,
                'url'=>'/v1/app/channel/ws/test_drive'
            ];
            $app = $this->newUser($app_data);
            Log::info('预约同步详情',[$app,$app_data]);
            if ($app->code != 0){
                return $this->error($app->msg);
            }
            $rc = RcMessage::query()->create($data);
            return $this->success($rc,'成功');
        }catch (\Exception $exception){
            Log::error('预约错误',[$exception->getMessage()]);
            return $this->error($exception->getMessage());
        }

    }

    /**
     * 登录
     */
    public function login($data)
    {
        $data['url'] = 'v1/app/channel/white/ws/login';
        return $this->newUser($data);

    }


    /**
     * 签名参数：
     * sk：test_sk【①】
     * name: 由我方提供【②】
     * time:当前时间戳(秒级)
     * 签名规则：
     * sk,name,time 拼接后的字符串md5运算
     * 如：sign=md5(test_sk测试时间戳)
     * 公共Headers：
     * Ak:由我方提供【③】
     * App_Version:1.0.0
     * Device: 由我方提供【④】
     * 接口请求公共参数：
     * sign:签名
     * time:签名时间戳
     * 请求接口域名：
     * 布发布环境：https://pre-api.bhmc.com.cn/
     * 生产环境：https://bm2-api.bluemembers.com.cn/
     * 测试环境：https://test-api.bluemembers.com.cn/
     * token = eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2hpZCI6IjFlNDgzMTY3Zjc1ZTQ4NmFiMWNmZDU3NGExNTM2ZjkxIiwidXNlcl9uYW1lIjoi56em5rWL6K-VIiwiZXhwIjoxNjMwMDU2ODMwLCJpc3MiOiJnby5taWNyby5zcnYudXNlciJ9.JpNqvE_Pfoo7CH_fnAK0s63LenilcQaDaerpGfYT4s0
     */
    public function newUser($data)
    {
        try {
            $time = time();
            $sk = 'c933ebaf79b2952e595d1479c4d330ac';
            $name = 'ws活动';
            $sign = md5($sk . $name . $time);

            $header = [
                'Content-Type' => 'application/json',
                'Ak' => '190697a2cfd4a9908d5efd1e72394b95',
                'Device' => 'ws_h5',
                'App_Version' => '1.0.0',
                'Token'=>(isset($data['token'])&&!empty($data['token']))?$data['token']:''
            ];
            $params = [
                'time' => $time,
                'sign' => $sign,
            ];
            $params = array_merge($data, $params);
            $client = new Client(['base_uri' => env('APP_URL'), 'timeout' => 5.0,'http_errors' => false]);
        $response = $client->post($data['url'], ['headers' => $header, 'json' => $params]);
        $data = $response->getBody()->getContents();
            return json_decode($data);
        }catch (\Exception $exception){
            Log::error('接口调取错误',[$exception->getMessage()]);
        }
    }


    /**
     *经销商列表
     */
    public function dealerList(Request  $request)
    {
        try {
            $city_code = $request->input('city_code');
            $data = [
                'city_code'=>$city_code,
                'url' => 'v1/app/channel/white/ws/dealer_list?city_code='.$city_code
            ];
            $dealer = $this->newUser($data);
            if ($dealer->code != 0){
                return $this->error($dealer->msg);
            }
            return  $this->success($dealer->data,'成功');
        }catch (\Exception $exception){
            Log::error('经销商错误',[$exception->getMessage()]);
            return  $this->error($exception->getMessage());
        }

    }

    public function car(Request $request){
        $data=['page_no'=>1,'page_size'=>20,'url'=>'v1/car/white/style/app_list'];
        $res = $this->newUser($data);
        if ($res->code !=0){
            return $this->error($res->msg);
        }
        return $this->success($res->data,'成功');
    }

    public function code(Request  $request)
    {
        $validator = Validator::make($request->all(), [
            'phone' => 'required'
        ]);

        if ($validator->fails()) {
            return $this->error($validator->errors()->first());
        }
        $data = $request->input();
        $header = [
            'Content-Type' => 'application/x-www-form-urlencoded',
            'Ak' => '190697a2cfd4a9908d5efd1e72394b95',
            'Device' => 'ws_h5',
            'App_Version' => '1.0.0',
        ];
        $client = new Client(['base_uri' => env('APP_URL'), 'timeout' => 5.0,]);
        $response = $client->post('v1/app/white/sms', ['headers' => $header, 'form_params' => ['phone'=>$data['phone']]]);
        $data = json_decode($response->getBody()->getContents());
        if ($data->code != 0){
            return  $this->error($data->msg);
        }

        return  $this->success('','成功');

    }
}
